<template>
    <h1>具体信息</h1>
    <div v-if="resourceInformation">
        <div v-if="resourceInformation">
            <p><strong>ID:</strong> {{ resourceInformation.id }}</p>
            <p><strong>资源名称:</strong> {{ resourceInformation.resourceName }}</p>
            <p><strong>资源类型:</strong> {{ resourceInformation.resourceType }}</p>
            <p><strong>版本:</strong> {{ resourceInformation.version }}</p>
            <p><strong>自定义名称:</strong> {{ resourceInformation.customerName }}</p>
            <p><strong>更新时间:</strong> {{ resourceInformation.updateTime }}</p>
            <p><strong>下载次数:</strong> {{ resourceInformation.downloadCount }}</p>
            <p><strong>描述:</strong> {{ resourceInformation.description }}</p>
            <p><strong>提供者:</strong> {{ resourceInformation.providerName }}</p>
        </div>
        <div v-else>
            <DelayedDisplay>
                <p>获取失败</p>
            </DelayedDisplay>
        </div>
    </div>


    <div v-if="imageList.length > 0">
        <div v-for="(image, index) in imageList" :key="index" style="margin-bottom: 10px;">
            <img :src="image" alt="资源图片" style="max-width: 100%; height: auto;" />
        </div>
    </div>
    <div v-else>
        <DelayedDisplay>
            <p>未上传图片</p>
        </DelayedDisplay>
    </div>

    <button @click="download">下载</button>

</template>

<script lang="ts" setup>
import { Resource } from '@/model/resource'
import { useRoute } from 'vue-router'
import { onMounted, ref } from 'vue'
import { getResourceImagesAPI, getResourceInformationAPI } from '@/service/API'
import DelayedDisplay from '@/components/DelayedDisplay.vue'

const route = useRoute()
const imageList = ref<string[]>([])
const resourceInformation = ref<Resource | null>(null)
let resourceId = Number(route.params.id)


const getResource = async () => {

    const { success1, resource } = await getResourceInformationAPI(resourceId)
    if (success1) {
        console.log('资源信息已加载');

        resourceInformation.value = resource
    } else {
        console.log('资源信息未加载' + success1);
    }
    const { success2, images } = await getResourceImagesAPI(resourceId)
    if (success2 && images) {
        console.log('资源图片已加载' + success2);
        imageList.value = images
    } else {
        console.log('资源图片未加载' + success2);
    }

}


const download = () => {
    console.log("开始下载资源 id：" + resourceId)

    // 构造下载 URL
    const url = `/api/resources/download/${resourceId}`

    // 创建一个隐藏的 <a> 元素
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', '') // 有的浏览器需要这个才能下载
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
}

onMounted(() => {
    getResource()
})
</script>

<style scoped></style>